
/**
 * Created by   fairytale110
 * Creat date   2017/5/14
 * Copy Right   fairytale110@foxmail.com
 * Description
 */
package com.huaxin.hxcloud.find.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.FindInfo;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.find.FindAdapter;
import com.huaxin.hxcloud.frendcircles.FrendCircleActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@SuppressWarnings("all")
public class ListFragment extends BaseListFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    private FindAdapter findAdapter;
    @BindView(R.id.recyclerview)
    RecyclerView       mRecyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean canRef = false;
    //
    List<FindInfo.QuestionListBean> questionList = new ArrayList<>();
    private final static int TYPE_REFRESH = 1;
    private final static int TYPE_MORE    = 2;
    private              int mType        = 0;
    private int                   mTabSelectPosition;//mTabSelectPosition
    private LocalBroadcastManager localBroad;

    private int lastVisibleItemPosition;
    private boolean flags = true;
    private View mNetWorkErrorView;
    private View mNoDataView;

    private int mPage = 0;

    public static ListFragment newInstance(int type, int tabSelectPosition) {

        ListFragment fragment = new ListFragment();
        Bundle args = new Bundle();
        args.putInt("TYPE", type);
        args.putInt("TAB_SELECT_POSITION", tabSelectPosition);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        Bundle bundle = getArguments();
        mType = bundle.getInt("TYPE");
        if (mType == 0) {
            mType = 6;
        }
        mTabSelectPosition = bundle.getInt("TAB_SELECT_POSITION");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_viewpager_list;
    }

    @Override
    public int getLoadFrameId() {
        return R.id.content;
    }


    /*
    * 懒加载的方法，
    * */
    @Override
    protected void lazyLoad() {
        super.lazyLoad();
    }

    @Override
    protected void initData() {
        tooglePager(false);
        //适配器
        findAdapter = new FindAdapter(getContext(), questionList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(findAdapter);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        findAdapter.setOnLoadMoreListener(this, mRecyclerView);
        //网络错误页面
        mNetWorkErrorView = LayoutInflater.from(getContext()).inflate(R.layout.static_network_error, (ViewGroup) mRecyclerView.getParent(), false);
        mNetWorkErrorView.findViewById(R.id.network_error_view).setVisibility(View.VISIBLE);
        //空界面
        mNoDataView = LayoutInflater.from(getContext()).inflate(R.layout.static_no_data, (ViewGroup) mRecyclerView.getParent(), false);
        mNoDataView.findViewById(R.id.no_data_ll).setVisibility(View.VISIBLE);

        onItemClickListener();
    }

    FindInfo findInfo;

    @Override
    protected void requestData() {
        if (getCache(mType) != null) {
            findInfo = getGson().fromJson(getCache(mType), FindInfo.class);
            findAdapter.setNewData(findInfo.getQuestionList());
            Log.d(TAG, "requestData: ----->缓存");
        } else {
            Log.d(TAG, "requestData: ----->请求数据");
            //请求数据
            ApiRequsetData(mType, TYPE_REFRESH, 0);
            flags = false;
        }
    }

    /**
     * 请求发现数据
     *
     * @param type
     * @param loadtype
     * @param pagno
     */
    private void ApiRequsetData(final int type, final int refreshState, final int page) {
        Call<FindInfo> findInfoCall = RequestHelper.getRequestApi().requestFindData(type, page);
        autoClose(findInfoCall);
        findInfoCall.request().url();
        Log.d(TAG, "ApiRequsetData: ---->" + findInfoCall.request().url());
        findInfoCall.enqueue(new Callback<FindInfo>() {
            @Override
            public void onResponse(Call<FindInfo> call, Response<FindInfo> response) {
                if (response.isSuccessful()) {
                    FindInfo body = response.body();
                    List<FindInfo.QuestionListBean> questionList = body.getQuestionList();
                    switch (refreshState) {
                        case TYPE_REFRESH://下拉刷新
                            if (questionList==null || questionList.size() == 0) {
                               // findAdapter.getData().clear();
                                findAdapter.setEmptyView(mNoDataView);
                            } else {
                                findAdapter.setNewData(questionList);
                                //设置缓存数据
                                setCache(type, body);
                            }
                            mSwipeRefreshLayout.setRefreshing(false);
                            findAdapter.setEnableLoadMore(true);
                            findAdapter.loadMoreComplete();
                            break;
                        case TYPE_MORE://上拉加载更多
                            if (questionList==null || questionList.size() == 0) {
                                findAdapter.loadMoreEnd(false);
                            } else {
                                findAdapter.setEnableLoadMore(true);
                                findAdapter.addData(questionList);
                                findAdapter.loadMoreComplete();
                            }
                            mSwipeRefreshLayout.setEnabled(true);

                            break;
                    }
                    return;
                }

            }

            @Override
            public void onFailure(Call<FindInfo> call, Throwable t) {
                ToastUtil.showToast("网络故障");
                findAdapter.setEmptyView(mNetWorkErrorView);
            }
        });
    }


    /**
     * 设置缓存
     *
     * @param type 缓存标记
     * @param body 缓存内容
     */
    private void setCache(int type, FindInfo body) {
        getACache().remove(getsSwitchType(type));
        getACache().put(getsSwitchType(type), getGson().toJson(body));
    }

    /**
     * 获取缓存信息
     *
     * @param type
     */
    private String getCache(int type) {
            String cacheStr = getACache().getAsString(getsSwitchType(type));
            if (cacheStr != null) {
            return cacheStr;
        }
        return null;
    }

    /**
     * 获取选择type
     * <p>
     * 0 = 全部的问题
     * 1 = 同企业用户的
     * 2 = 好友的
     * 3 = 自己收藏的
     * 4 = 关注的用户的
     * 5 = 自己的
     * 6 = 行业(圈子)
     *
     * @param type
     * @return
     */
    private String getsSwitchType(int type) {
        String flag = null;
        switch (type) {
            case 6:
                flag = Constants.AC_DISCOVER_INFO_All;
                break;
            case 1:
                flag = Constants.AC_DISCOVER_INFO_FIRM;
                break;
            case 2:
                flag = Constants.AC_DISCOVER_INFO_FRIEND;
                break;
            case 4:
                flag = Constants.AC_DISCOVER_INFO_FOCUS;
                break;
            case 5:
                flag = Constants.AC_DISCOVER_INFO_MIME;
                break;
        }
        return flag;
    }


    private int mLoginMode = -1;

    @Override
    public View getSlidableView() {
        return mRecyclerView;
    }

    /**
     * @desc 监听点击事件
     * @author songxf
     * created at 2017/8/11 11:23
     */
    private void onItemClickListener() {
        findAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final FindInfo.QuestionListBean mQuestionListBean = findAdapter.getItem(position);
                final List<FindInfo.QuestionListBean> mListBeen = findAdapter.getData();
                final int questionId = mQuestionListBean.getQuestionId();
                switch (view.getId()) {
                    case R.id.item_find_ll_layout://点击条目
                        Intent intent = new Intent(getContext(), FrendCircleActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("user", mQuestionListBean);
                        intent.putExtras(bundle);
                        /*intent.putExtra("position", position);
                        intent.putExtra("type", mType);*/
                        getContext().startActivity(intent);
                        break;
                }
            }
        });
    }

    /**
     * 收藏EventBus
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void collectEvent(CollectDataEventBus message) {
        int questionId = message.getQuestionId();
        int collectNum = message.getCollectNum();
        boolean collect = message.isCollect();
        Log.d(TAG, "refreshEvent: ----->" + message.toString());
        findAdapter.refreshCollectData(questionId, collect, collectNum);
    }

    /**
     * 点赞EventBus
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void likeEvent(LikeDataEventBus message) {
        int questionId = message.getQuestionId();
        int likeNum = message.getLikeNum();
        boolean like = message.isLike();
        FindInfo.LikeerArrayBean likeerArray = message.getLikeerArray();
        Log.d("---", "--111111->" + message.toString());
        findAdapter.refreshListData(questionId, like, likeNum, likeerArray);
    }

    /**
     * 关注EventBus
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void focusEvent(FocusDataEventBus message) {
        int userId = message.getUserId();
        boolean focus = message.isFocus();
        findAdapter.refreshFocusData(userId, focus);
    }

    /**
     * 评论EventBus
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentEvent(CommentEventBus message) {
        int questionId = message.getQuestionId();
        boolean like = message.isLike();
        int likeNum = message.likeNum;
        boolean isCollect = message.isCollect();
        int commentCount = message.getCommentCount();
        int collentNum = message.getCollentNum();
        List<FindInfo.LikeerArrayBean> likeerArray = message.getLikeerArray();

        Log.d(TAG, "commentEvent: ---->" + message.toString());
        findAdapter.refreshCommentData(questionId, like, likeNum, isCollect, collentNum, commentCount, likeerArray);
    }

    /**
     * 关注删除 刷新数据 EventBus
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(RefreshDataEvent message) {
        if (message.isRefresh) {
            ApiRequsetData(mType, TYPE_REFRESH, 0);
        }
    }

    /**
     * 评论数据的添加和删除 EventBus
     *
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentSucceedEvent(HxCommentContentEventBus message) {
        FindInfo.QuestionListBean.PartialTopCommentArrBean commentArrBean = message.getCommentArrBean();
        int questionId = message.getQuestionId();
        int commentState = message.getCommentState();
        findAdapter.refreshCommentSucceedData(commentArrBean, questionId, commentState);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public void tooglePager(boolean isHeader) {
        Log.d(TAG, "tooglePager: --->" + isHeader);
        mSwipeRefreshLayout.setEnabled(isHeader);
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        findAdapter.setEnableLoadMore(false);
        mPage = 0;
        ApiRequsetData(mType, TYPE_REFRESH, mPage);
        Log.d(TAG, "onRefresh: ---刷新->");
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        //少于一页的数量
        if (findAdapter.getData().size() < 10) {
            findAdapter.loadMoreEnd(true);
        } else {
            mPage++;
            //加载更多操作,下拉暂时不可用
            mSwipeRefreshLayout.setEnabled(false);
            ApiRequsetData(mType, TYPE_MORE, mPage);
            Log.d(TAG, "onRefresh: ---加载更多->");
        }
    }

    public RecyclerView getRvList() {
        return mRecyclerView;
    }
}
